<?php

namespace App\Services;

use App\Models\Attachment;
use Illuminate\Http\UploadedFile;
use OSS\OssClient;
use OSS\Core\OssException;

class UploadService
{
    public function upload(UploadedFile $file)
    {
        //动态方法选择驱动方式。
        $method = config('site.upload.drive','local');

        return $this->$method($file);

    }

    public function local(UploadedFile $file)
    {
        //构建本地路径

        $path = '/attachments/' . $file->store(date('y/m'), 'attachment');
        return $this->save($file, $path);
    }

    public function oss(UploadedFile $file)
    {
        //在站点配置中配置参数
        $accessKeyId = config('site.aliyun.accessKeyId');
        $accessKeySecret = config('site.aliyun.accessKeySecret');
        $endpoint = config('site.aliyun.oss.endpoint');
        $bucket = config('site.aliyun.oss.bucket');
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

        //文件名
        $object = user('id') . date('ymdhis') . mt_rand(1000, 9999) . '.' . $file->extension();

        $info = $ossClient->uploadFile($bucket, $object, $file->path());
        return $this->save($file, $info['oss-request-url']);

    }

    public function save(UploadedFile $file, string $path)
    {
        //文件信息纯如数据付，即path（位置）,name（主名字),extension(扩展名)
        return Attachment::create(
            [
                'path' => $path,
                'name' => $file->getClientOriginalName(),
                'extension' => $file->extension(),
                'user_id'=>user('id')
            ]
        );
    }
}
